package com.wk.slaveNodes;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;

import com.wk.job.Job;

public class RecieveJobs implements Runnable{

	final int PORT = 8081;
	ServerSocket server = null;
	LinkedBlockingQueue<Job> jobs =null;
	boolean isWorking = true;
	
	public RecieveJobs( LinkedBlockingQueue<Job> jobs) {
		 this.jobs= jobs;
		 initServer();
		 System.out.println("RecieveJobs Initted!! ");
	}
	public boolean initServer(){
		try {
			this.server = new ServerSocket(PORT);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean closeServer() {
		try {
			this.server.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	@Override
	public void run() {
		while(isWorking){
			try {
				System.out.println("等待远程连接。。。");
				Socket socket = server.accept();
				ObjectInputStream objobin = new ObjectInputStream(socket.getInputStream());
				DataOutputStream out = new DataOutputStream(socket.getOutputStream()); 
				
				String message = "SUCESS";
				try {
					Job job = (Job)objobin.readObject();
					if(job != null){
						jobs.add(job);
						message = "SUCESS";
						System.out.println(message+" "+jobs.size()+" "+job.toString());
					}else{
						
						message = "FAILD";
						System.out.println(message);
					}
					out.writeUTF(message);
					out.flush();
					
					
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				objobin.close();
				out.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	
	
	
}
